package database

import (
	"card/pkg/logger"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"time"
)

var (
	daoOnce  sync.Once
	database = make(map[string]*gorm.DB)
)

func Connection(dbConfig map[string]interface{}) {
	for k, v := range dbConfig {
		dao, err := gorm.Open(mysql.New(mysql.Config{
			DSN: getDsn(v.(map[string]interface{})),
		}), &gorm.Config{
			Logger: logger.NewGormLogger(),
		})
		if err != nil {
			panic(fmt.Sprintf("数据库%s初始化失败，错误原因：%v", k, err))
		}
		sqlDB, err := dao.DB()
		if err != nil {
			panic(fmt.Sprintf("获取数据库对象失败,数据库是%s,错误是%v", k, err))
		}
		// 设置最大连接数
		sqlDB.SetMaxOpenConns(v.(map[string]interface{})["max_open_connection"].(int))
		// 设置最大空闲连接数
		sqlDB.SetMaxIdleConns(v.(map[string]interface{})["max_idle_connections"].(int))
		// 设置每个链接的过期时间
		sqlDB.SetConnMaxLifetime(time.Duration(v.(map[string]interface{})["max_life_seconds"].(int)) * time.Second)
		database[k] = dao
	}
}
func getDsn(dbConfig map[string]interface{}) string {
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&multiStatements=true&loc=%s",
		dbConfig["username"],
		dbConfig["password"],
		dbConfig["host"],
		dbConfig["database"],
		dbConfig["charset"],
		dbConfig["parse_time"],
		dbConfig["local"],
	)
	return dsn
}
func GetDao(name string) *gorm.DB {
	return database[name]
}
